package com.example.springboot.controller.bigfileinput;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jodd.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/12/19 15:06
 */
@RestController
@RequestMapping("/czk/mulThread")
@Api(tags = "多线程导入文件")
public class ThreadPoolReadController {
    @GetMapping("/input")
    @ApiOperation(value = "导入")
    public String input() {
        ExecutorService executorService = new ThreadPoolExecutor(
                5,
                10,
                60,
                TimeUnit.SECONDS,
                // 阻塞队列
                new ArrayBlockingQueue<>(100),
                // 线程名称
                new ThreadFactoryBuilder().setNameFormat("nzq-%d").get(),
                (r, executor) -> {
                    // 线程池没被关闭
                    if (!executor.isShutdown()) {
                        try {
                            executor.getQueue().put(r);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
        );
        try (LineIterator iterator = IOUtils.lineIterator(new FileInputStream("test.txt"), "utf-8")) {
            while (iterator.hasNext()) {
                String next = iterator.next();
                executorService.submit(() -> {
                    // 导入
                    System.out.println(Thread.currentThread().getName() + " 导入数据 " + next);
                });
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return "导入成功";
    }
}
